import React, { forwardRef, useEffect, useRef, useState } from "react";
import PropTypes from 'prop-types'
import { Input, Keyboard, Popup, Toast } from "zarm";
import s from './style.module.less';
import cx from 'classnames';
import PopupDate from "../PopDate";
import dayjs from "dayjs";
import CustomIcon from "../CustomIcon";
import { get, typeMap } from '@/utils';
import { post } from "../../utils";
import {Close} from "@zarm-design/icons";

const PopupAddBill = forwardRef(({ detail ={}, onReload},ref) => {
    const id = detail && detail.id // 外部传进来的账单详情id

    const [show, setShow] = useState(false)
    // 支出或收入类型
    const [payType, setPayType] = useState('expense')
    const [amount, setAmount] = useState('')
    const [currentType, setCurrentType] = useState({})
    const [expense, setExpense] = useState([])
    const [income, setIncome] = useState([])

    const [remark, setRemark] = useState('')
    const [showRemark, setShowRemark] = useState(false)

    useEffect(() => {
        if (detail.id) {
            setPayType(detail.pay_type == 1 ? 'expense' : 'income')
            setCurrentType({
                id: detail.type_id,
                name: detail.type_name
            })
            setRemark(detail.remark)
            setAmount(detail.amount)
            setDate(dayjs(Number(detail.date)).$d)
        }
    },[detail])
    const getType = async () => {
        const { data: {list} } = await get('/api/type/list')
        const _expense = list.filter(i => i.type == 1)
        const _income = list.filter(i => i.type == 2)
        setExpense(_expense)
        setIncome(_income)
        // 没有id说明是新添加账单
        if (!id) setCurrentType(_expense[0])
    }

    useEffect(() => {
        getType()
    },[])

    const dateRef = useRef()
    const [date, setDate] = useState(new Date())

    const changeType = (type) => {
        setPayType(type)
    }

    if (ref) {
        ref.current = {
            show: () => {
                setShow(true)
            },
            close: () => {
                setShow(false)
            }        
        }
    }
    // 日期选择
    const choseDate = (val) => {
        setDate(val)
    }
    // 监听输入框改变值
    const handleMoney = (value) => {
        value = String(value)
        // 点击删除按钮时
        if (value == 'delete') {
            let _amount = amount.slice(0, amount.length - 1)
            setAmount(_amount)
            return
        }
        // 点击确认按钮
        if (value == 'ok') {
            // 处理账单
            addBill()
            return
        }
        // 输入值为“.”时，且已经存在小数点，则不让其继续字符串拼接
        if (value == '.' && amount.includes('.')) return
        // 小数点后超过两位，不继续拼接
        if (value != '.' && amount.includes('.') && amount && amount.split('.')[1].length >= 2) return
        // 
        setAmount(amount + value)

    }
    // 添加账单
    const addBill = async () => {
        if (!amount) {
            Toast.show('请输入金额')
            return
        }
        const params = {
            amount: Number(amount).toFixed(2),
            type_id: currentType.id,
            type_name: currentType.name,
            date: dayjs(date).unix() * 1000,
            pay_type: payType == 'expense' ? 1 : 2,
            remark: remark || ''
        }
        // 判断是否有id，有则调用更新接口
        if (id) {
            params.id = id
            const result = await post('api/bill/update',params)
            Toast.show('更新成功')
        } else {
            const result = await post('/api/bill/add',params)
            // 重置数据
            setAmount('')
            setPayType('expense')
            setCurrentType(expense[0])
            setDate(new Date())
            setRemark('')

            Toast.show('添加成功')
        }

        setShow(false)
        if (onReload) onReload()
    }
    return <Popup
        visible={show}
        direction="bottom"
        onMaskClick={() => setShow(false)}
        destroy={false}
        mountContainer={() => document.body}
    >
       <div className={s.addWrap}>
            <header className={s.header}>
                <Close className={s.close} onClick={() => setShow(false)}/>
            </header>
            <div className={s.filter}>
                <div className={s.type}>
                    <span onClick={() => changeType('expense')} className={cx({[s.expense]: true,[s.active]: payType == 'expense'})}>支出</span>
                    <span onClick={() => changeType('income')} className={cx({[s.income]: true,[s.active]: payType == 'income'})}>收入</span>
                </div>
                <div className={s.time}
                        onClick={() => dateRef.current && dateRef.current.show()}
                    >
                        {dayjs(date).format('MM-DD')}
                    </div>
                <PopupDate ref={dateRef} onSelect={choseDate}/>
            </div>
            <div className={s.money}>
                <span className={s.sufix}>￥</span>
                <span className={cx(s.amount, s.animation)}>{amount}</span>
            </div>
            <div className={s.typeWrap}>
                <div className={s.typeBody}>
                {
                    (payType === 'expense' ? expense : income).map(item => <div
                        onClick={() => setCurrentType(item)} key={item.id} className={s.typeItem}
                    >
                        <span className={cx({[s.iconfontWrap]: true,[s.expense]: payType === 'expense',[s.income]: payType === 'income',[s.active]: currentType.id === item.id })}>
                            <CustomIcon className={s.iconfont} type={typeMap[item.id]?.icon}/>
                        </span>
                        <span>{item.name}</span>
                    </div>)
                }
                </div>
            </div>
            {/* 备注 */}
            <div className={s.remark}>
                {
                    showRemark ? <Input
                        autoHeight
                        showLength
                        maxLength={50}
                        type="text"
                        rows={3}
                        value={remark}
                        placeholder="请输入备注信息"
                        onChange={(e) => setRemark(e.target.value)}
                        onBlur={() => setShowRemark(false)} 
                    /> : <span onClick={() => setShowRemark(true)}>{remark || '添加备注'}</span>
                }
            </div>
            {/* 键盘 */}
            <Keyboard type="price" onKeyClick={(value) => handleMoney(value)}/>
       </div>
    </Popup>
})

export default PopupAddBill